﻿using System.Threading.Tasks;
using DailyPoetryX.Models;
using DailyPoetryX.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;

namespace DailyPoetryX.ViewModels {
    public class DetailPageViewModel : ViewModelBase {
        /******** 构造函数 ********/

        private IFavoriteStorage favoriteStorage;

        public DetailPageViewModel(IFavoriteStorage favoriteStorage) {
            this.favoriteStorage = favoriteStorage;
        }

        /******** 绑定属性 ********/

        public Poetry Poetry {
            get => _poetry;
            set {
                Set(nameof(Poetry), ref _poetry, value);
                newPoetry = true;
            }
        }

        private Poetry _poetry;

        public Favorite Favorite {
            get => _favorite;
            set => Set(nameof(Favorite), ref _favorite, value);
        }

        private Favorite _favorite;

        public bool Loading {
            get => _loading;
            set => Set(nameof(Loading), ref _loading, value);
        }

        private bool _loading;

        /******** 绑定命令 ********/

        public RelayCommand PageAppearingCommand =>
            _pageAppearingCommand ?? (_pageAppearingCommand = new RelayCommand(
                async () => {
                    var run = false;

                    if (newPoetry) {
                        lock (newPoetryLock) {
                            if (newPoetry) {
                                newPoetry = false;
                                run = true;
                            }
                        }
                    }

                    if (!run) return;

                    Loading = true;
                    var favorite =
                        await favoriteStorage.GetFavoriteAsync(Poetry.Id) ??
                        new Favorite {PoetryId = Poetry.Id};
                    isFavorite = favorite.IsFavorite;
                    Favorite = favorite;
                    Loading = false;
                }));

        private RelayCommand _pageAppearingCommand;

        public RelayCommand FavoriteToggledCommand =>
            _favoriteToggledCommand ?? (_favoriteToggledCommand =
                new RelayCommand(async () => {
                    if (isFavorite == Favorite.IsFavorite) return;
                    isFavorite = Favorite.IsFavorite;

                    Loading = true;
                    await favoriteStorage.SaveFavoriteAsync(Favorite, true);
                    Loading = false;
                }));

        private RelayCommand _favoriteToggledCommand;

        /******** 私有变量 ********/

        private bool newPoetry;
        private readonly object newPoetryLock = new object();
        private bool isFavorite;
    }
}